| Total Complexity | 9 |
| Total Lines | 46 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
| 1 | import { AxiosRequestConfig } from 'axios'; |
||
| 4 | |||
| 5 | /** |
||
| 6 | * Auth interceptor. |
||
| 7 | * It responsible to add Authorization header if it needs. |
||
| 8 | */ |
||
| 9 | export default class AuthInterceptor extends RequestInterceptor { |
||
| 10 | |||
| 11 | /** |
||
| 12 | * If present it adds access token to Authorization header. |
||
| 13 | * |
||
| 14 | * @param config The axios request config |
||
| 15 | */ |
||
| 16 | public requestHandler(config: AxiosRequestConfig): Promise<AxiosRequestConfig> { |
||
| 17 | config = this.setAuthorizationHeader(config); |
||
| 18 | |||
| 19 | // Authorization header set so go ahead |
||
| 20 | if (config.headers?.Authorization) { |
||
| 21 | return Promise.resolve(config); |
||
| 22 | } |
||
| 23 | |||
| 24 | // trying client credentials auth so go ahead |
||
| 25 | if (config.url === '/auth' && config.data?.grant_type === GrantType.ClientCredentials) { |
||
| 26 | return Promise.resolve(config); |
||
| 27 | } |
||
| 28 | |||
| 29 | if (!this.beditaClient.getConfig('clientId')) { |
||
| 30 | return Promise.resolve(config); |
||
| 31 | } |
||
| 32 | |||
| 33 | return this.beditaClient |
||
| 34 | .clientCredentials() |
||
| 35 | .then(() => Promise.resolve(this.setAuthorizationHeader(config))); |
||
| 36 | } |
||
| 37 | |||
| 38 | /** |
||
| 39 | * Set Authorization header if not already set and access token is present. |
||
| 40 | * |
||
| 41 | * @param config The axios request config |
||
| 42 | */ |
||
| 43 | protected setAuthorizationHeader(config: AxiosRequestConfig): AxiosRequestConfig { |
||
| 44 | const accessToken = this.beditaClient.getStorageService().accessToken; |
||
| 45 | if (accessToken && !config.headers?.Authorization) { |
||
| 46 | config.headers.Authorization = `Bearer ${accessToken}`; |
||
| 47 | } |
||
| 48 | |||
| 49 | return config; |
||
| 50 | } |
||
| 52 |